import 'dart:async';
import 'dart:isolate';

import 'package:floating_timer/comunication.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:move_to_background/move_to_background.dart';
import 'package:system_alert_window/system_alert_window.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

@pragma('vm:entry-point')
void callBack(String tag) {
  WidgetsFlutterBinding.ensureInitialized();
  SendPort? port = IsolateManager.lookupSendPort();
  if (port != null) {
    port.send(tag);
    // print('send $tag');
  }
}

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  bool _isShowingWindow = false;
  SystemWindowPrefMode prefMode = SystemWindowPrefMode.OVERLAY;
  int count = 0;
  //late Timer timer1;

  @override
  void initState() {
    super.initState();
    _initPlatformState();
    _requestPermissions();

    ReceivePort _port = ReceivePort();
    IsolateManager.registerPortWithName(_port.sendPort);
    _port.listen((dynamic callBackData) {
      String tag = callBackData as String;
      // print('recv $tag');
      switch (tag) {
        case "reset":
          count = 0;
          // print('set count=0');
          _updateTimerWindow(increase: false);
          break;
        default:
          break;
      }
    });

    SystemAlertWindow.registerOnClickListener(callBack);
  }

  @override
  void dispose() {
    //SystemAlertWindow.removeOnClickListener();
    SystemAlertWindow.closeSystemWindow(prefMode: prefMode);
    super.dispose();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> _initPlatformState() async {
    await SystemAlertWindow.enableLogs(true);
    String? platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await SystemAlertWindow.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion ?? 'null';
    });
  }

  Future<void> _requestPermissions() async {
    await SystemAlertWindow.requestPermissions(prefMode: prefMode);
  }

  final int windowWidth = 120;
  final int windowHeight = 35;

  void _showTimerWindow() {
    var now = DateTime.now();
    var formator = DateFormat.Hms();
    var nowText = '${formator.format(now)} - ${count++}';
    var color1 = Colors.white;
    var color2 = Colors.lightBlue;
    if (!_isShowingWindow) {
      //   timer1 = Timer(const Duration(seconds: 1), () {
      //     _updateTimerWindow();
      //     if (!_isShowingWindow) {
      //       timer1.cancel();
      //     }
      //   });

      Future.doWhile(() async {
        // print('update timer window $count');
        _updateTimerWindow();
        var ret = await Future.delayed(
            const Duration(seconds: 1), () => _isShowingWindow);
        return ret;
      });
      // SystemWindowHeader header =
      //     SystemWindowHeader(title: SystemWindowText(text: nowText));
      SystemWindowHeader header = SystemWindowHeader(
        button: SystemWindowButton(
          text: SystemWindowText(
            text: nowText,
            padding: SystemWindowPadding(left: 0, right: 0, top: 0, bottom: 0),
            textColor: color1,
          ),
          tag: 'reset',
          padding: SystemWindowPadding(left: 0, right: 0, top: 0, bottom: 0),
          margin: SystemWindowMargin(left: 0, right: 0, top: 0, bottom: 0),
          width: windowWidth,
          height: windowHeight,
          decoration:
              SystemWindowDecoration(startColor: color2, endColor: color2),
        ),
        padding: SystemWindowPadding(left: 0, right: 0, top: 0, bottom: 0),
        buttonPosition: ButtonPosition.CENTER,
      );
      SystemAlertWindow.showSystemWindow(
        height: windowHeight,
        width: windowWidth,
        header: header,
        gravity: SystemWindowGravity.TOP,
        notificationTitle: 'Time',
        notificationBody: nowText,
        prefMode: prefMode,
        backgroundColor: Colors.transparent,
      );
      setState(() {
        _isShowingWindow = true;
      });
    }
  }

  int _colorChangeSenconds = 60;

  void _updateTimerWindow({bool increase = true}) {
    var now = DateTime.now();
    var formator = DateFormat.Hms();
    var nowText = '${formator.format(now)} - $count';
    var color1 = Colors.white;
    var color2 = Colors.lightBlue;
    if (increase) {
      count++;
    }
    if (count > _colorChangeSenconds) {
      color1 = Colors.yellow;
      color2 = Colors.red;
    }
    if (_isShowingWindow) {
      //   timer1 = Timer(const Duration(seconds: 1), () {
      //     _updateTimerWindow();
      //     if (!_isShowingWindow) {
      //       timer1.cancel();
      //     }
      //   });
      SystemWindowHeader header = SystemWindowHeader(
        button: SystemWindowButton(
          text: SystemWindowText(
            text: nowText,
            padding: SystemWindowPadding(left: 0, right: 0, top: 0, bottom: 0),
            textColor: color1,
          ),
          tag: 'reset',
          padding: SystemWindowPadding(left: 0, right: 0, top: 0, bottom: 0),
          margin: SystemWindowMargin(left: 0, right: 0, top: 0, bottom: 0),
          width: windowWidth,
          height: windowHeight,
          decoration:
              SystemWindowDecoration(startColor: color2, endColor: color2),
        ),
        padding: SystemWindowPadding(left: 0, right: 0, top: 0, bottom: 0),
        buttonPosition: ButtonPosition.CENTER,
      );
      SystemAlertWindow.updateSystemWindow(
        height: windowHeight,
        width: windowWidth,
        header: header,
        gravity: SystemWindowGravity.TOP,
        notificationTitle: 'Time',
        notificationBody: nowText,
        prefMode: prefMode,
      );
    }
  }

  void _closeTimerWindow() {
    setState(() {
      _isShowingWindow = false;
    });
    SystemAlertWindow.closeSystemWindow(prefMode: prefMode);
    count = 0;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('简单悬浮时钟'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              Text('Running on: $_platformVersion\n'),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: MaterialButton(
                  onPressed: _showTimerWindow,
                  textColor: Colors.white,
                  child: const Text('显示时钟'),
                  color: Colors.deepOrange,
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: MaterialButton(
                  onPressed: _closeTimerWindow,
                  textColor: Colors.white,
                  child: const Text('关闭时钟'),
                  color: Colors.deepOrange,
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: MaterialButton(
                  onPressed: () {
                    MoveToBackground.moveTaskToBack();
                  },
                  textColor: Colors.white,
                  child: const Text('后台运行'),
                  color: Colors.deepOrange,
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: TextField(
                  onChanged: (value) {
                    try {
                      _colorChangeSenconds = int.parse(value);
                    } catch (e) {
                      _colorChangeSenconds = 60;
                    }
                  },
                  decoration: const InputDecoration(
                    labelText: '颜色切换时间(默认60秒)',
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
